package com.st.common.security;

import com.st.common.convert.SysUserConvert;
import com.st.domain.SysRole;
import com.st.domain.SysUser;
import com.st.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.stream.Collectors;

/**
 * @author shent
 */
@Service("SwordUserDetailsService")
public class SwordUserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    SysUserConvert sysUserConvert;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = this.sysUserService.getByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException(username);
        }
        SwordUserDetails swordUserDetails = sysUserConvert.domainToSword(user);
        swordUserDetails.setRoles(this.sysUserService.getRolesById(user.getId()).stream().map(SysRole::getName).collect(Collectors.toList()));
        swordUserDetails.setResourcesIds(this.sysUserService.getResourceCodesByUserId(user.getId()));
        return swordUserDetails;
    }

}
